//
//  CallViewController.m
//  NewChat
//
//  Created by songKX on 16/3/11.
//  Copyright © 2016年 蓝鸥. All rights reserved.
//

#import "CallViewController.h"
#import "FLCircleLayout.h"
#import "SKXCallViewController.h"
#define kCalcAngle(x) x * M_PI / 180.0

@interface CallViewController ()
@property (weak, nonatomic) IBOutlet UILabel *tryBtn;
@property (weak, nonatomic) IBOutlet UILabel *sureLabel;
@property (nonatomic , strong) UICollectionView * headCollectionView;
@property (nonatomic , strong) NSMutableArray *headRoundArray;

@property (weak, nonatomic) IBOutlet UIView *headRoundView;
@property (weak, nonatomic) IBOutlet UIButton *suijiBtn;
@property (nonatomic , strong) NSTimer *timer;
@property (weak, nonatomic) IBOutlet UIStackView *daojishiBtn;
@property (nonatomic, assign) BOOL flag;
@property (nonatomic , assign) NSInteger count;
@property (nonatomic , strong) NSMutableArray *arcRondArray;
@property (nonatomic , assign) BOOL suijiFlag;

@end

@implementation CallViewController

-(NSMutableArray *)arcRondArray{
    
    if (_arcRondArray == nil) {
        _arcRondArray = [[NSMutableArray alloc] init];
    }
    
    return  _arcRondArray;
    
}

-(NSMutableArray *)headRoundArray{
    
    if (_headRoundArray == nil) {
        _headRoundArray =[NSMutableArray new];
    }
    return _headRoundArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.flag = NO;
    self.count = 0;
    self.suijiFlag = NO;
    self.navigationController.navigationBar.translucent = NO;
    
    [self.navigationController.navigationBar setHidden:YES];
    
    self.tabBarController.tabBar.translucent = NO;
    
    self.tryBtn.transform = CGAffineTransformMakeRotation(M_PI*1.8);
    
    self.sureLabel.transform = CGAffineTransformMakeRotation(M_PI/4);
    
    
    self.headRoundView.backgroundColor = nil;
    
    [self setRoundView];
    
    
    
    // Do any additional setup after loading the view from its nib.
}

//初始化圆形环绕视图

-(void)setRoundView{
    

    
    for (int i = 0; i < 6; i++) {
        
        UIButton *temp = [[UIButton alloc] init];
        
        temp.backgroundColor = nil;
        
        temp.size = CGSizeMake(70, 70);
        temp.layer.masksToBounds = YES;
        
        temp.layer.cornerRadius = 35;
        
        temp.tag = 101+i;
        temp.enabled = NO;
        
        [temp addTarget:self action:@selector(chooseSomeOneToTalk:) forControlEvents:(UIControlEventTouchUpInside)];
        
        [temp setImage:[UIImage imageNamed:@"bofang22"] forState:UIControlStateNormal];
        
        // 半径100
        CGFloat radius = 120;
        
        // 圆心
        CGFloat circleX = self.headRoundView.frame.size.width * 0.5;
        CGFloat circleY = self.headRoundView.frame.size.height * 0.5;
        
        
        CGFloat singleItemAngle = 360.0 / 6;
        
        // 计算各个环绕的图片center
        temp.center = CGPointMake(circleX + radius * cosf(kCalcAngle(singleItemAngle * i)), circleY - radius * sinf(kCalcAngle(singleItemAngle * i)));
        
        
        [self.headRoundArray addObject:temp];
        [self.headRoundView addSubview:temp];
        
    }
    
}

-(void)requestAllOnlineUsersDidFinished{
    
    RealReachability *reachability = [RealReachability sharedInstance];
    ReachabilityStatus status = [reachability currentReachabilityStatus];
    
    if (status != 0) {
        
        
        
        self.arcRondArray = [[NSMutableArray alloc] init];
        
        AVQuery *query = [AVUser query];
        [query includeKey:@"status"];
        [query whereKey:@"status" equalTo:@"在线"];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            
            NSMutableArray *tempArray = [NSMutableArray arrayWithArray:objects];
            
            NSInteger a = objects.count;
            
            NSInteger b = 0;
            
            
            
            
            for (int i = 0;i < tempArray.count;i++) {
                
                if ([tempArray[i][@"username"] isEqualToString:[AVUser currentUser].username]) {
                    
                    [tempArray removeObjectAtIndex:i];
                    a = tempArray.count;
                }
            }
            
            for (int i = 0; i < 6; i++) {
                
                
                b = arc4random()%a;
                
                [self.arcRondArray addObject:tempArray[b]];
                
                [tempArray removeObjectAtIndex:b];
                
                a = tempArray.count;
                if (a == 0) {
                    
                    break;
                    
                }
                
                
            }
            
            NSInteger c = 0;
            
            for (AVObject * obj in self.arcRondArray) {
                
                NSLog(@"---%@",obj[@"username"]);
                
                //背景图片赋值
                
                UIButton *btnTemp = self.headRoundArray[c];
                
                btnTemp.enabled = YES;
                
                [self.headRoundArray[c]setBackgroundImage:[UIImage imageNamed:obj[@"userImageName"]] forState:UIControlStateNormal];
                c++;
                
                
            }
            
            if (self.suijiFlag) {
                
                self.suijiBtn.hidden = YES;
                
                self.daojishiBtn.hidden = NO;
                
            }
            
        }];
        
    }else{
        
        UIAlertAction * sure = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        UIAlertController *alt = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前无网络连接" preferredStyle:UIAlertControllerStyleAlert];
        
        [alt addAction:sure];
        [self presentViewController:alt animated:YES completion:nil];
        
    }
    
}


-(void)chooseSomeOneToTalk:(UIButton *)sender{
    
    AVObject *chater = self.arcRondArray[sender.tag - 101];
    
    
    
    
    SKXCallViewController *temp = [[SKXCallViewController alloc] init];
    
    
    
    temp.chatPerson = chater;
    
    temp.chater = chater[@"username"];
    
    EMBuddy *tempBody = [EMBuddy buddyWithUsername:chater[@"username"]];
    
    temp.chaterBudy = tempBody;
    
    [self.navigationController pushViewController:temp animated:YES];
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)suijiAction:(UIButton *)sender {
    
    RealReachability *reachability = [RealReachability sharedInstance];
    ReachabilityStatus status = [reachability currentReachabilityStatus];
    
    if (status != 0) {
        
        self.suijiFlag = YES;
        [self addTimer];

        
    }
    
    
    
    
    
    [self requestAllOnlineUsersDidFinished];
    
    
}

//添加定时器
-(void)addTimer{
    
    
    self.timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(againAutoLogin) userInfo:nil repeats:YES];
    
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
}
//取消定时器
-(void)cancelTimer{
    
    [self.timer invalidate];
    self.timer = nil;
    
    self.count = 0;
    
}
-(void)againAutoLogin{
    
    UILabel * temp =[self.daojishiBtn.arrangedSubviews lastObject];

    
    self.count += 1;
    
    temp.text = [NSString stringWithFormat:@"00:%02ld",59-self.count];
    
    
    NSLog(@"定时器");
    
    if (self.count ==59) {
        
        [self cancelTimer];
        
        self.suijiBtn.hidden = NO;
        
        self.daojishiBtn.hidden = YES;
        
        
        temp.text = @"00:59";
        
        
    }
    
}

- (IBAction)chooseTalkSomeOne:(UIButton *)sender {
    
    
    RealReachability *reachability = [RealReachability sharedInstance];
    ReachabilityStatus status = [reachability currentReachabilityStatus];
    
    if (status != 0) {
        
        AVQuery *query = [AVUser query];
    [query includeKey:@"status"];
    [query whereKey:@"status" equalTo:@"在线"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        
        NSInteger a = objects.count;
        
        NSInteger b = arc4random()%a;
        
        AVObject * chater = objects[b];
        
        NSMutableArray *temparray = [NSMutableArray arrayWithArray:objects];
        
        if ([chater[@"username"] isEqualToString:[AVUser currentUser].username]) {
            
            [temparray removeObjectAtIndex:b];
            
            a = temparray.count;
            b = arc4random()%a;
            chater = temparray[b];
            
        }
        
        SKXCallViewController *temp = [[SKXCallViewController alloc] init];
        
        temp.chatPerson = chater;
        
        EMBuddy *tempBody = [EMBuddy buddyWithUsername:chater[@"username"]];
        
        temp.chaterBudy = tempBody;
        
        temp.chater = chater[@"username"];
        
        [self.navigationController pushViewController:temp animated:YES];
        
        
    }];
    
    }else{
        
        UIAlertAction * sure = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        UIAlertController *alt = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前无网络连接" preferredStyle:UIAlertControllerStyleAlert];
        
        [alt addAction:sure];
        [self presentViewController:alt animated:YES completion:nil];
        
    }
    
    
    }

-(void)viewWillAppear:(BOOL)animated{
    
    
    self.tabBarController.tabBar.hidden = NO;
    
    self.navigationController.navigationBar.translucent = NO;
    
    self.tabBarController.tabBar.translucent = NO;
    
}

@end
